package com.text.service.impl;

import com.text.entity.Course;
import com.text.entity.StudentAndCourse;
import com.text.repository.CourseRepository;
import com.text.repository.StudentAndCourseRepository;
import com.text.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private StudentAndCourseRepository studentAndCourseRepository;

    // 获取课程信息
    @Override
    public Course getCourse(String id) {
        return courseRepository.findById(id).orElse(null);
    }

    // 获取所有课程
    @Override
    public List<Course> getAllCourses() {
        return courseRepository.findAll();
    }

    // 添加课程
    @Override
    public void addCourse(Course course) {
        courseRepository.save(course);
    }

    // 更新课程信息
    @Override
    public boolean updateCourse(String id, Course updatedCourse) {
        Optional<Course> existingCourseOptional = courseRepository.findById(id);
        if (existingCourseOptional.isPresent()) {
            Course existingCourse = existingCourseOptional.get();

            // 更新字段
            existingCourse.setCourseName(updatedCourse.getCourseName());
            existingCourse.setCredit(updatedCourse.getCredit());
            existingCourse.setDescription(updatedCourse.getDescription());

            // 保存更新后的课程信息
            courseRepository.save(existingCourse);
            return true;
        }
        return false;
    }

    // 删除课程
    @Override
    public boolean deleteCourse(String id) {
        Optional<Course> existingCourse = courseRepository.findById(id);
        if (existingCourse.isPresent()) {
            courseRepository.deleteById(id);
            return true;
        }
        return false;
    }
}